package cn.iocoder.yudao.module.call.controller.open.record;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.call.controller.admin.acsnlpresult.vo.AcsNlpResultPageReqVO;
import cn.iocoder.yudao.module.call.controller.admin.acsnlpresult.vo.AcsNlpResultRespVO;
import cn.iocoder.yudao.module.call.controller.admin.record.vo.CallRecordRespVO;
import cn.iocoder.yudao.module.call.dal.dataobject.acsnlpresult.AcsNlpResultDO;
import cn.iocoder.yudao.module.call.dal.dataobject.ivrintentionlabelstatistics.IvrIntentionLabelStatisticsDO;
import cn.iocoder.yudao.module.call.dal.dataobject.record.CallRecordDO;
import cn.iocoder.yudao.module.call.dal.dataobject.record.CallRecordTranslateDO;
import cn.iocoder.yudao.module.call.enums.CallTypeEnum;
import cn.iocoder.yudao.module.call.enums.IvrKeywordsBranchTypeEnum;
import cn.iocoder.yudao.module.call.service.acsnlpresult.AcsNlpResultService;
import cn.iocoder.yudao.module.call.service.ivrintentionlabelstatistics.IvrIntentionLabelStatisticsService;
import cn.iocoder.yudao.module.call.service.record.CallRecordService;
import cn.iocoder.yudao.module.crm.api.clue.CrmClueApi;
import cn.iocoder.yudao.module.crm.api.clue.dto.CrmClueDTO;
import cn.iocoder.yudao.module.crm.api.contact.CrmContactApi;
import cn.iocoder.yudao.module.crm.api.contact.dto.CrmContactDTO;
import cn.iocoder.yudao.module.crm.api.customer.CrmCustomerApi;
import cn.iocoder.yudao.module.crm.api.customer.dto.CrmCustomerDTO;
import cn.iocoder.yudao.module.crm.api.level.CrmLevelConfigApi;
import cn.iocoder.yudao.module.crm.api.level.dto.CrmLevelConfigDTO;
import cn.iocoder.yudao.module.ent.api.company.EntCompanyApi;
import cn.iocoder.yudao.module.ent.document.EntCompany;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "呼叫中心 - 通话录音")
@RestController
@RequestMapping("/call/record")
@Validated
@Slf4j
public class CallRecordOpenController {

    @Resource
    private CallRecordService callRecordService;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private EntCompanyApi entCompanyApi;

    @Resource
    private CrmCustomerApi crmCustomerApi;

    @Resource
    private CrmContactApi crmContactApi;

    @Resource
    private CrmClueApi crmClueApi;



    @Resource
    private CrmLevelConfigApi crmLevelConfigApi;

    @Resource
    private IvrIntentionLabelStatisticsService ivrIntentionLabelStatisticsService;

    @Resource
    private AcsNlpResultService acsNlpResultService;

    @GetMapping("/get")
    @Operation(summary = "通话详情")
    @TenantIgnore
    public CommonResult<CallRecordRespVO> getRecord(@RequestParam("reqNo") String reqNo) {
        CallRecordDO record = callRecordService.getRecordByReqNo(reqNo);

        if (Objects.isNull(record)) {
            return success(null);
        }
        CallRecordRespVO result = BeanUtils.toBean(record, CallRecordRespVO.class);

        if (Objects.equals(1, record.getTransStatus())) {
            CallRecordTranslateDO callRecordTranslateDO = callRecordService.getRecordTranslate(record.getId());
            if (Objects.nonNull(callRecordTranslateDO)) {
                result.setContent(callRecordTranslateDO.getContent());
                result.setSummary(callRecordTranslateDO.getSummary());
            }
        }

        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(ListUtil.of(result.getOwnerUserId()));
        buildRespVO(result, userMap);



        if (record.getCallType().equals(CallTypeEnum.BATCH_IVR_CALL.getValue())) {
            //ivr类型的查对应意向信息
            IvrIntentionLabelStatisticsDO ivrIntentionLabelStatisticsDO = ivrIntentionLabelStatisticsService.getByCallId(record.getReqNo());
            if (ivrIntentionLabelStatisticsDO != null) {
                result.setFlowId(ivrIntentionLabelStatisticsDO.getFlowId());
                result.setCallId(ivrIntentionLabelStatisticsDO.getCallId());
                result.setMingzhongsuoyouwenti(ivrIntentionLabelStatisticsDO.getMingzhongsuoyouwenti());
                result.setMingzhongyewuwenti(ivrIntentionLabelStatisticsDO.getMingzhongyewuwenti());
                result.setKendingcishu(ivrIntentionLabelStatisticsDO.getKendingcishu());
                result.setJujuecishu(ivrIntentionLabelStatisticsDO.getJujuecishu());
                result.setKehujianghuacishu(ivrIntentionLabelStatisticsDO.getKehujianghuacishu());
                result.setTonghuashichang(ivrIntentionLabelStatisticsDO.getTonghuashichang());
                result.setKehutonghuaneirong(ivrIntentionLabelStatisticsDO.getKehutonghuaneirong());
                result.setKehutonghuaneirongKeys(ivrIntentionLabelStatisticsDO.getKehutonghuaneirongKeys());
                result.setZouwanzhuliucheng(ivrIntentionLabelStatisticsDO.getZouwanzhuliucheng() == 1 ? "是" : "否");
                result.setKehuzuihouyijuhua(IvrKeywordsBranchTypeEnum.getNameByType(ivrIntentionLabelStatisticsDO.getKehuzuihouyijuhua()) );
                result.setLevel(ivrIntentionLabelStatisticsDO.getLevel());
                CrmLevelConfigDTO crmLevelConfigDTO = crmLevelConfigApi.getLevelConfig(ivrIntentionLabelStatisticsDO.getLevel());
                if (crmLevelConfigDTO != null) {
                    result.setLevelName(crmLevelConfigDTO.getName());
                }

            }
        }
        return success(result);
    }

    public void buildRespVO(CallRecordRespVO item, Map<Long, AdminUserRespDTO> userMap) {
        MapUtils.findAndThen(userMap, item.getOwnerUserId(), user -> item.setOwnerUserName(user.getNickname()));
        // 判断source
        if (Objects.isNull(item.getSource())) {
            item.setSourceName("自动外呼");
        } else if (item.getSource().equals("none")) {
            item.setSourceName("手拨");
        } else {
            if (StrUtil.isNotEmpty(item.getSourceId())) {
                switch (item.getSource()) {
                    case "ent":
                        // 从企业大数据查找entName
                        EntCompany companyByEntId = entCompanyApi.getEntCompanyByEntId(item.getSourceId());
                        if (Objects.nonNull(companyByEntId)) {
                            item.setSourceName(companyByEntId.getCompanyName());
                        }
                        break;
                    case "clue":
                        // 从clue查找
                        CrmClueDTO clueByClueId = crmClueApi.getClueByClueId(Long.parseLong(item.getSourceId()));
                        if (Objects.nonNull(clueByClueId)) {
                            item.setSourceName(clueByClueId.getName());
                        }
                        break;
                    case "customer":
                        // 从customer查找
                        CrmCustomerDTO customerByCustomerId = crmCustomerApi.getCustomerByCustomerId(Long.parseLong(item.getSourceId()));
                        if (Objects.nonNull(customerByCustomerId)) {
                            item.setSourceName(customerByCustomerId.getName());
                        }
                        break;
                    case "contact":
                        CrmContactDTO contactByContactId = crmContactApi.getContactByContactId(Long.parseLong(item.getSourceId()));
                        if (Objects.nonNull(contactByContactId)) {
                            item.setSourceName(contactByContactId.getName());
                        }
                        break;
                }
            }

        }
    }

    @GetMapping("/nlp-result")
    @Operation(summary = "获得对话记录列表")
    @TenantIgnore
    public CommonResult<List<AcsNlpResultRespVO>> getAcsNlpResultSimpleList(@Valid AcsNlpResultPageReqVO pageReqVO) {
        List<AcsNlpResultDO> acsNlpResultSimpleList = acsNlpResultService.getAcsNlpResultSimpleList(pageReqVO);
        return success(BeanUtils.toBean(acsNlpResultSimpleList, AcsNlpResultRespVO.class));
    }


}
